package com.xywl.escort.view.user.login

import android.os.Bundle
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.trello.rxlifecycle2.LifecycleTransformer
import com.xywl.escort.R
import com.xywl.escort.base.BaseActivity
import com.xywl.escort.bean.LoginReq
import com.xywl.escort.bean.LoginResp
import com.xywl.escort.common.Constant
import com.xywl.escort.common.PreferenceKeys.*
import com.xywl.escort.utils.*
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_login.*
import timber.log.Timber
import javax.inject.Inject

@Route(path = "/xy/login")
class LoginActivity : BaseActivity(), LoginContract.View {

    @Inject
    lateinit var mPresenter: LoginContract.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        showBackButton()
        setTitleText(R.string.user_login)

        mPresenter.takeView(this)

        text_register.setOnClickListener {
            ARouter.getInstance().build("/xy/register").navigation()
        }

        text_recover_pwd.setOnClickListener {
            ARouter.getInstance().build("/xy/pwd/recover").navigation()
        }

        btn_confirm.setOnClickListener {
            login()
        }
    }

    private fun login() {
        val account = edit_account.text.toString().trim()
        val pwd = edit_pwd.text.toString().trim()

        if (!NetworkUtil.isAvailable(this)) {
            ToastUtil.showTip(this, R.string.network_error)
            return
        }

        if (!RegexUtils.checkMobile(account)) {
            ToastUtil.showTip(this, R.string.user_error_hint_phone)
            return
        }
        if (checkAccountAndPwd(account, pwd)) {
            val password = MD5.encrypt(pwd)
            val req = LoginReq()
            req.account = account
            req.pwd = password
            req.deviceId = UUIDUtil.getDeviceId(this)
            mPresenter.login(req)
        }
    }

    private fun checkAccountAndPwd(account: String, pwd: String): Boolean {
        if (TextUtils.isEmpty(account)) {
            ToastUtil.showTip(this, R.string.user_account_hint_account)
            return false
        } else if (TextUtils.isEmpty(pwd)) {
            ToastUtil.showTip(this, R.string.user_account_hint_password)
            return false
        } else if (pwd.length < Constant.Length.MIN_PAY_PWD_LENGTH) {
            ToastUtil.showTip(this, R.string.user_account_reset_password_error)
            return false
        }
        return true
    }

    override fun isActive(): Boolean {
        return false
    }

    override fun <T : Any?> bindToLife(): LifecycleTransformer<T> {
        return this.bindToLifecycle()
    }

    override fun loginSuccess(dataBean: LoginResp.DataBean?) {
        ToastUtil.showTip(this, "登录成功")
        RxSPTool.putBoolean(this, IS_FIRST_OPEN, false)
        val token = dataBean!!.token
        if (!TextUtils.isEmpty(token)) {
            RxSPTool.putString(this, TOKEN, token)
        }
        val account = dataBean.account
        if (!TextUtils.isEmpty(account)) {
            RxSPTool.putString(this, PHONE, account)
        }
        val userId = dataBean.id
        if (!TextUtils.isEmpty(userId)) {
            RxSPTool.putString(this, USER_ID, userId)
        }
        val headImg = dataBean.headImg
        if (!TextUtils.isEmpty(headImg)) {
            RxSPTool.putString(this, HEAD_IMG, headImg)
        }
        val nickName = dataBean.nickname
        if (!TextUtils.isEmpty(nickName)) {
            RxSPTool.putString(this, NICK_NAME, nickName)
        }

        if (!TextUtils.isEmpty(account)) {
            val pushService = PushServiceFactory.getCloudPushService()
            pushService.bindAccount(account, object : CommonCallback {
                override fun onSuccess(response: String) {
                    Timber.e("bindAccount response=$response")
                }

                override fun onFailed(errorCode: String, errorMessage: String) {
                    Timber.e("bindAccount failed -- errorCode:$errorCode -- errorMessage:$errorMessage")
                }
            })
        }
        finish()
    }

    override fun loginFailure(msg: String) {
        ToastUtil.showTip(this, msg)
    }
}
